package club.baibin0558.jstudy.service.impl;

import club.baibin0558.jstudy.core.po.JStudyNode;
import club.baibin0558.jstudy.core.repertory.JStudyNodeRepository;
import club.baibin0558.jstudy.service.JStudyNodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 类别保存服务实现
 *
 * @author 白彬
 */
@Service
public class JStudyNodeServiceImpl implements JStudyNodeService {
    private static final String CACHE_KEY_SELECT_TREE = "jstudy-node-selectTree";
    private static final String CACHE_KEY_SELECT_LIST = "jstudy-node-selectList";
    private static final String TOP_CODE = "-1";
    @Autowired
    private JStudyNodeRepository jStudyNodeRepository;

    /**
     * 根据父类code查询儿子
     *
     * @param parentCode
     * @return
     */
    @Override
    @Cacheable(value = CACHE_KEY_SELECT_TREE,key="#parentCode")
    public List<JStudyNode> selectList(String parentCode) {
        return jStudyNodeRepository.findAllByParentCodeEquals(parentCode);
    }

    /**
     * 保存
     *
     * @param node
     * @return
     */
    @Override
    @CacheEvict(value = {CACHE_KEY_SELECT_TREE,CACHE_KEY_SELECT_LIST})
    public JStudyNode save(JStudyNode node) {
        if(node.getId() == null) {
            node.setId(System.currentTimeMillis());
        }
        return jStudyNodeRepository.save(node);
    }

    /**
     * 移除
     *
     * @param id
     * @return
     */
    @Override
    @CacheEvict(value = {CACHE_KEY_SELECT_TREE,CACHE_KEY_SELECT_LIST})
    public JStudyNode remove(Long id) {
        Optional<JStudyNode> jStudyNode = jStudyNodeRepository.findById(id);
        jStudyNodeRepository.deleteById(id);
        return jStudyNode.get();
    }

    /**
     * 查询所有
     *
     * @return
     */
    @Override
    @Cacheable(value = CACHE_KEY_SELECT_TREE)
    public JStudyNode selectTree() {
        List<JStudyNode> all = jStudyNodeRepository.findAll();
        JStudyNode result = new JStudyNode();
        result.setCode(TOP_CODE);
        recursion(all,result);
        return result;
    }
    private void recursion(List<JStudyNode> all,JStudyNode result) {
        List<JStudyNode> removeList = new ArrayList<>();
        all.forEach(node -> {
            if(node.getParentCode().equals(result.getCode())) {
                result.getChildren().add(node);
                removeList.add(node);
            }
        });
        all.removeAll(removeList);
        result.getChildren().forEach(node -> recursion(all,node));
    }


}
